package com.huang.day9;


import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author HuangShen
 * @Description
 * @create 2021-04-08 7:41
 */
public class MyTest {
    public static void main(String[] args) {


        ThreadPool threadPool = new ThreadPool(1, 1000, TimeUnit.MILLISECONDS, 1);

        for (int i = 0; i < 4; i++) {
            int j=i;
            threadPool.execute(()->{
                try {
                    Thread.sleep(1000);
                    double k=(double) 25/ 2;
                    System.out.println("执行任务"+j+"---"+k);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}


/**
 * 线程池类
 */
class ThreadPool {
    private BlockQueue<Runnable> taskQueue;
    private HashSet<Worker> works = new HashSet<>();
    private long timeout;
    private TimeUnit timeUnit;
    private int coreSize;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int capacity) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockQueue<>(capacity);

    }

    public void execute(Runnable task){
        synchronized (works) {
            if (works.size()<coreSize){
                Worker worker = new Worker(task);
                works.add(worker);
                worker.start();
            }else {
                taskQueue.put(task);
                // 任务队列满时等待策略
                //1 一直进行等待
                //2
            }
        }

    }

    class Worker  extends Thread{

        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }


        @Override
        public void run() {
            //1 执行当前任务
            //2 执行 完毕 看 任务队列是否有任务
            while (task!=null|| (task=taskQueue.take())!=null){
                try {
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task=null;
                }
            }

            synchronized (works){
                works.remove(this);
            }

        }
    }
}

/**
 * 阻塞队列 类
 *
 * @param <T>
 */
class BlockQueue<T> {

    //共享队列 双向队列
    private ArrayDeque<T> queue = new ArrayDeque<T>();
    //锁
    private ReentrantLock lock = new ReentrantLock();
    //3.生产者条件变量
    private Condition fullWaitSet = lock.newCondition();
    //4.消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();

    //线程池容量
    private int capacity;

    public BlockQueue(int capacity) {
        this.capacity = capacity;
    }

    /**
     * 带超时时间的 等待
     *
     * @param time 时间
     * @param unit 单位
     * @return r
     */
    public T poll(long time, TimeUnit unit) {

        long l = unit.toNanos(time);

        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    if (l <= 0) {
                        return null;
                    }
                    l = emptyWaitSet.awaitNanos(l);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            capacity--;
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }

    }

    //从队列中取任务
    public T take() {
        lock.lock();
        try {
            //任务队列满时等待
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            capacity--;
            fullWaitSet.signalAll();
            return t;
        } finally {
            lock.unlock();
        }
    }

    //项任务队列中添加任务
    public void put(T t) {
        lock.lock();
        try {
            //任务队列满时等待
            while (queue.size() == capacity) {
                try {
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(t);
            capacity++;
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }


    /**
     * 返回队列中的任务数
     *
     * @return int
     */
    public int size() {
        lock.lock();
        try {
            return capacity;
        } finally {
            lock.unlock();
        }

    }


}